package controller

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntity"
	"gitee.com/fierce_wolf/go-fox-edge-common/commSql"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
	"gitee.com/fierce_wolf/go-fox-edge-common/httpserver"
	"go-fox-edge-kernel-manager/utils/PageUtils"
)

type deviceRecordManageController struct {
}

func (e *deviceRecordManageController) init() {
	httpserver.Server.POST("/device/record/page", e.selectEntityPage)
}

func (e *deviceRecordManageController) selectEntityPage(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	deviceName := Map.GetString(body, "deviceName", "")
	deviceType := Map.GetString(body, "deviceType", "")
	manufacturer := Map.GetString(body, "manufacturer", "")
	recordName := Map.GetString(body, "recordName", "")
	pageNum := Map.GetInt(body, "pageNum", 1)
	pageSize := Map.GetInt(body, "pageSize", 10)

	filter := ""
	if deviceName != "" {
		filter += " (device_name like '%" + deviceName + "%') AND"
	}
	if deviceType != "" {
		filter += " (device_type = '" + deviceType + "') AND"
	}
	if manufacturer != "" {
		filter += " (manufacturer = '" + manufacturer + "') AND"
	}
	if recordName != "" {
		filter += " (record_name = '" + recordName + "') AND"
	}
	if filter != "" {
		filter = filter[0 : len(filter)-len("AND")]
	}

	return e.selectEntityListPage(filter, "DESC", pageNum, pageSize)
}

func (e *deviceRecordManageController) selectEntityListPage(filter string, order string, pageNum int, pageSize int) (interface{}, error) {
	// 查询总数
	selectCount := PageUtils.MakeSelectCountSQL("tb_device_record", filter)

	total, err := commSql.QueryCount(selectCount)
	if err != nil {
		return nil, err
	}

	// 分页查询数据
	selectPage := PageUtils.MakeSelectSQLPage("tb_device_record", nil, nil, filter, order, pageNum, pageSize)
	entityList, err := commSql.Client.Query(edgeEntity.Type.DeviceRecordEntity.Type(), selectPage)
	if err != nil {
		return nil, err
	}

	mapList := commEntity.BuildMapList(entityList)

	data := make(map[string]interface{})
	data["list"] = mapList
	data["total"] = total

	return data, nil

}
